package com.wangjiang.mario.admin.system.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wangjiang.mario.admin.common.base.BaseServiceImpl;
import com.wangjiang.mario.admin.common.exception.FileDeleteException;
import com.wangjiang.mario.admin.common.exception.FileSaveException;
import com.wangjiang.mario.admin.common.exception.NoFoundException;
import com.wangjiang.mario.admin.common.util.CommonUtils;
import com.wangjiang.mario.admin.common.util.FileUploadUtils;
import com.wangjiang.mario.admin.common.util.FileUtils;
import com.wangjiang.mario.admin.system.domain.components.ConfigComponent;
import com.wangjiang.mario.admin.system.domain.entity.FileEntity;
import com.wangjiang.mario.admin.system.domain.mapper.FileMapper;
import com.wangjiang.mario.admin.system.domain.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileServiceImpl extends BaseServiceImpl<FileMapper, FileEntity>
        implements FileService {

    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);


    @Autowired
    private ConfigComponent configComponent;

    @Override
    public FileEntity getByFileName(String fileName) {
        QueryWrapper<FileEntity> defaultWrapper = getDefaultWrapper();
        defaultWrapper.eq("upload_filename", fileName);
        return getOne(defaultWrapper);
    }

    @Override
    public Boolean justSaveAsALog(String originName, String savedName) {
        FileEntity fileEntity = new FileEntity();
        fileEntity.setOriginFilename(originName);
        fileEntity.setExtension(getExtension(originName));
        fileEntity.setUploadFilename(savedName);
        return baseSave(fileEntity);
    }

    @Override
    public Boolean justSaveAsALog(String originName) {
        return justSaveAsALog(originName, originName);
    }

    @Override
    public String saveFile(MultipartFile file) {
        // 上传文件路径
        String fileName;
        try {
            String filePath = configComponent.getUploadRootPath();
            // 上传并返回新文件名称
            fileName = FileUploadUtils.upload(filePath, file);
            FileEntity fileEntity = new FileEntity();
            fileEntity.setOriginFilename(file.getOriginalFilename());
            fileEntity.setExtension(getExtension(file.getOriginalFilename()));
            fileEntity.setUploadFilename(fileName);
            baseSave(fileEntity);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new FileSaveException("文件保存错误");
        }

        return fileName;
    }

    /**
     * 根据文件名删除文件
     * 逻辑: 1. 查看上传路径是否有该文件存在，不存在报错
     * 2. 查看上传记录表，设置记录状态 设置status
     *
     * @param filename
     * @return
     */
    @Override
    public Boolean deleteFileByFilename(String filename) {
        String rootPath = configComponent.getUploadRootPath();
        String filePath = rootPath + filename;
        if (FileUtils.isExist(filePath)) {
            Boolean isDelete = FileUtils.deleteFile(filePath);
            if(isDelete) {
                FileEntity fileEntity = getByFileName(filename);
                if (CommonUtils.isNotNull(fileEntity)) {
                    // 文件已经删除  设置资源不存在
                    fileEntity.setHasResource(false);
                    baseUpdateById(fileEntity);
                }
            } else {
                throw new FileDeleteException("文件删除失败");
            }
        } else {
            throw new NoFoundException("文件不存在");
        }
        return true;
    }

    /**
     * 获取文件后缀名
     *
     * @param originalFilename
     * @return
     */
    private String getExtension(String originalFilename) {
        return originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
    }

}
